/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.webapp.controller.management.auxiliary;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.qinyeit.serviceapp.entity.*;
import com.qinyeit.serviceapp.service.auxiliary.CommentBranchService;
import com.qinyeit.serviceapp.service.auxiliary.CommentService;
import com.qinyeit.serviceapp.service.organization.BranchService;
import com.qinyeit.serviceapp.service.organization.DistrictService;
import com.qinyeit.webapp.controller.management.BaseManagementController;
import com.qinyeit.webapp.utils.CurrentAccountUtils;
import com.qinyeit.webapp.utils.SearchableUtils;
import com.qinyetech.springstage.core.date.DateUtils;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.utils.JSONUtils;
import com.qinyetech.springstage.core.web.annotation.PageableDefaults;
import com.qinyetech.springstage.core.web.annotation.PermissionInfo;
import com.qinyetech.springstage.core.web.dto.ResponseResult;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * ClassName: CommentsController <br/>
 * Function: comment [原因备注] <br/>
 * date: 2018-11-27 10:01:12 <br/>
 *
 * @author liuwenjin
 * @version  1.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/management/auxiliary/comments")
@PermissionInfo(parentName ="基础信息管理" ,parentOrder = 10,order = 10,code = "management_comment:read",name ="原因备注",deleteAble = false)
public class CommentsController extends BaseManagementController{

	@Autowired
	private CommentService commentService;
	@Autowired
	private DistrictService districtService;
	@Autowired
    private CommentBranchService commentBranchService;
	@Autowired
    private BranchService branchService;



	private final String [] keys = {"id","type","name","operatorName","operateTime","remark","branchs","sys"};

    @RequiresPermissions("management_comment:show")
    @PermissionInfo(code = "management_comment:show",name ="查看",deleteAble = false)
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    @PageableDefaults(sort = "id=desc")//默认按照id降序
    public ResponseResult<JSONObject> index(Searchable searchable){
        searchable = SearchableUtils.newSearchableWithMerchantFilter(searchable);
        Page<Comment> commentPage = commentService.findAll(searchable);
        searchable = SearchableUtils.newSearchableWithMerchantFilter();
        if(CollectionUtils.isNotEmpty(commentPage.getContent())){
            List<CommentBranch> branchList = null;
            String branchs = "";
            Branch branchEn = null;
            District district = null;
            int count =0;
            for (Comment comment : commentPage.getContent()) {
                branchs = "";
                count = 0;
                searchable.addSearchParam("commentId_eq",comment.getId());
                branchList = commentBranchService.findWithSort(searchable);
                if(CollectionUtils.isNotEmpty(branchList)){
                    for (CommentBranch branch : branchList) {
                        if (count<3){
                            branchEn = branchService.findById(branch.getBranchId());
                            district = districtService.findById(branch.getDistrictId());
                            branchs += branchEn.getName()+"("+district.getName()+")"+",";
                        }else {
                            break;
                        }
                        count++;
                    }
                }
                comment.setBranchs(StringUtils.isBlank(branchs)?"":branchs.substring(0,branchs.length()-1));
            }
        }
        return ok("查询成功", JSONUtils.include(commentPage, keys));
    }

    @GetMapping("/create")
    public ResponseResult<QyMap> _new(){
        QyMap map=QyMap.NEW();
        map.setv("comment",JSONUtils.include(new Comment(), keys));
        return ok("初始化成功", map);
    }

    @RequiresPermissions("management_comment:create")
    @PermissionInfo(code = "management_comment:create",name ="新增",deleteAble = false)
    @PostMapping("/create")
    public ResponseResult<String> create(@RequestBody JSONObject comment, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        commentService.saveData(comment,CurrentAccountUtils.getAuthenticatedMerchantGroupID(),CurrentAccountUtils.getAuthenticatedEmployeeName());
        return ok("保存成功");
    }

    @GetMapping("/{id}")
    public ResponseResult<JSONObject> show(@ModelAttribute Comment comment){
        return ok("查询成功", JSONUtils.include(comment, keys));
    }

    @GetMapping("/{id}/update")
    public ResponseResult<QyMap> edit(@ModelAttribute Comment comment){
        QyMap map=QyMap.NEW();
        map.setv("comment",JSONUtils.include(comment, keys));
        return ok("查询成功",map);
    }

    @RequiresPermissions("management_comment:update")
    @PermissionInfo(code = "management_comment:update",name ="修改",deleteAble = false)
    @PutMapping("/{id}/update")
    public ResponseResult<String> update(@ModelAttribute @Valid Comment comment,BindingResult bindingResult){
        Searchable searchable = SearchableUtils.buildExists(comment.getId(), "name", comment.getName());
        searchable.addSearchParam("type_eq",comment.getType());
        if(commentService.exists(searchable)){
            return fail("名称已存在");
        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        comment.setOperatorName(CurrentAccountUtils.getAuthenticatedEmployeeName());
        comment.setOperateTime(DateUtils.date());
        comment.setUpdateTimestamp(DateUtils.current());
        commentService.update(comment);
        return ok("更新成功", null);
    }

    @RequiresPermissions("management_comment:destory")
    @PermissionInfo(code = "management_comment:destory",name ="删除",deleteAble = false)
    @DeleteMapping("/{id}")
    public ResponseResult<String> destory(@PathVariable Long id){
        Comment comment = commentService.findById(id);
        comment.setUpdateTimestamp(DateUtils.current());
        commentService.update(comment);
        //删除明细
        commentService.deletedDetails(id);
        commentService.logicDelete(id);
        //将分店的对应数据的删除
        commentService.deletedBranchCommentData(comment);
        return ok("删除成功", null);
    }


    /**
     * 分配门店 初始化
     * @param id
     * @return
     */
    @GetMapping("/allocationBranch")
    public ResponseResult<String> allocationBranch(Long id){
        QyMap map = QyMap.NEW();
        initFormDate(map);
        if (id!=null){
            Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
            searchable.addSearchParam("commentId_eq",id);
            List<CommentBranch> branchList = commentBranchService.findWithSort(searchable);
            Branch branchEn = null;
            if(CollectionUtils.isNotEmpty(branchList)){
                for (CommentBranch branch : branchList) {
                    branchEn = branchService.findById(branch.getBranchId());
                    branch.setLabel(branchEn.getName());
                }
            }
            map.setv("branchList",JSONUtils.include(branchList,"id","branchId","districtId","label"));
        }
        return ok("查询成功", map);
    }


    /**
     * 分配门店 保存 (可批量分配机构)
     * @param data
     * @return
     */
    @RequiresPermissions("management_comment:allocationBranch")
    @PermissionInfo(code = "management_comment:allocationBranch",name ="分配门店",deleteAble = false)
    @PostMapping("/allocationBranch")
    public ResponseResult<String> allocationBranchSave(@RequestBody JSONObject data){
        commentService.allocationBranchSave(data);
        return ok("保存成功");
    }

    /**
     * 查看所有门店
     *
     * @param id
     * @return
     */
//    @RequiresPermissions("management_comment:showAllBranchs")
//    @PermissionInfo(code = "management_comment:showAllBranchs",name ="查看门店",deleteAble = false)
    @GetMapping("/showAllBranchs")
    public ResponseResult<String> showAllBranchs(Long id){
        Comment comment = commentService.findById(id);
        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("commentId_eq",comment.getId());
        List<CommentBranch> branchList = commentBranchService.findWithSort(searchable);
        Branch branch = null;
        if(CollectionUtils.isNotEmpty(branchList)){
            for (CommentBranch commentBranch : branchList) {
                branch = branchService.findById(commentBranch.getBranchId());
                commentBranch.setLabel(branch.getName());
            }
        }
        return ok("操作成功", JSONUtils.include(branchList,"id","branchId","districtId","label"));
    }

    @ModelAttribute
    public void preparedData(@PathVariable(value="id",required = false) String id,Model model){
        if(StringUtils.isNotBlank(id)){ //如果路径中有id参数则查询实体对象
            Comment comment = commentService.findById(Long.valueOf(id));
            model.addAttribute(comment);
        }
    }

    /**
     * 初始化表单数据
     * @param qyMap
     */
    private void initFormDate(QyMap qyMap){
        //区域门店
        //用户权限
        qyMap.setv("districts",getDistricts());
//        String dataPermissions = CurrentAccountUtils.getAuthenticatedManageBranch();
//        if (CurrentAccountUtils.getAuthenticatedIsAdmin()){
//            List<District> list=districtService.getBuildTree(CurrentAccountUtils.getAuthenticatedMerchantGroupID(),true);
//            qyMap.setv("districts",list);
//        }else {
//            List<Long> branchIds = null;
//            if (StringUtils.isNotBlank(dataPermissions)){
//                branchIds = JSON.parseArray(dataPermissions,Long.class);
//            }
//            List<District> list=districtService.getBuildTree(CurrentAccountUtils.getAuthenticatedMerchantGroupID(),true,branchIds,true);
//            qyMap.setv("districts",list);
//        }
    }

}